<template>
  <transition name="my-alert-fade">
    <!--  判断样式和是否有关闭按钮 -->
    <div
      v-show="isShow"
      class="my-alert"
      ref="alert"
      :class="[`my-alert--${type} ${isDark}`, { 'is-center': center }]"
    >
      <!-- 内容 -->
      <div class="my-alert__content">
        <span class="my-alert__title">
          <!-- 判断是否有title的具名插槽，有的话显示， 没有显示title的值 -->
          <slot v-if="$slots.title" name="title" />
          <!-- 使用template不会生成标签占用 -->
          <template v-else>
            {{ title }}
          </template>
        </span>
        <!-- 关闭按钮 -->
        <i
          v-if="closable"
          @click="onClose"
          class="my-alert__closebtn iconfont icon-close"
        ></i>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "myAlert",
  data() {
    return {
      isShow: true,
    };
  },
  props: {
    title: {
      type: String,
      default: "提示信息",
    },
    type: {
      type: String,
      default: "info",
      validate(v) {
        return ["success", "warning", "info", "error"].includes(v);
      },
    },
    center: {
      type: Boolean,
      default: false,
    },
    closable: {
      type: Boolean,
      default: true,
    },
    effect: {
      type: String,
    },
  },
  methods: {
    onClose() {
      this.isShow = false;
      this.$emit("close");
    },
  },
  computed: {
    isDark() {
      return this.effect == "dark" ? "is-dark" : "is-light";
    },
  },
};
</script>

<style lang="less">
.my-alert-fade-enter,
.my-alert-fade-leave-active {
  opacity: 0;
}
.my-alert {
  width: 100%;
  padding: 8px 16px;
  margin: 0;
  box-sizing: border-box;
  border-radius: 4px;
  position: relative;
  background-color: #fff;
  overflow: hidden;

  display: flex;
  align-items: center;
  transition: opacity 0.2s;
  // 成功

  &.my-alert--success {
    &.is-light {
      background-color: #f0f9eb;
      color: #67c23a;
    }
    &.is-dark {
      background-color: #67c23a;
      color: #fff;
    }
  }
  // 信息
  &.my-alert--info {
    &.is-light {
      background-color: #f4f4f5;
      color: #909399;
    }
    &.is-dark {
      background-color: #909399;
      color: #fff;
    }
  }
  // 警告
  &.my-alert--warning {
    &.is-light {
      background-color: #fdf6ec;
      color: #e6a23c;
    }
    &.is-dark {
      background-color: #e6a23c;
      color: #fff;
    }
  }
  // 错误
  &.my-alert--error {
    &.is-light {
      background-color: #fef0f0;
      color: #f56c6c;
    }
    &.is-dark {
      background-color: #f56c6c;
      color: #fff;
    }
  }
  // 是否居中
  &.is-center {
    justify-content: center;
  }
  .my-alert__content {
    display: table-cell;
    padding: 0 8px;
  }
  .my-alert__title {
    font-size: 13px;
    line-height: 18px;
  }

  .my-alert__closebtn {
    font-size: 12px;
    opacity: 1;
    position: absolute;
    top: 12px;
    right: 15px;
    cursor: pointer;
    &::before {
      color: #c0c4cc;
    }
  }
}
</style>
